var basePath = $("#basePath").val();
var objects = null;

$(document).ready(function (){
        menuCss("用户");
        var url = basePath + "/user/queryUserTermInit";
        publicAjax(url,"POST",{"type":"user_type"},function (data){
                if(data.ret == 200){
                    objects = data.data;
                    initQueryUserData();
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                    return;
                }
        });
    queryUserList(0,10);
    $("#show-count").change(function(){
        queryUserList(0,$("#show-count").val());
    })
    initModel();
    bindEvent();
    //initSelectCss();
    $('input[type="radio"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    $("#aaa").click(function (){
        var url = basePath+"/largeScreen/initData";
        publicAjax(url,"POST",{},function (data) {
           console.log(JSON.stringify(data));
        });
    });
});

function initSelectCss(){
    $("#add-update-from").find("select").select2({language:'zh-CN', placeholder:'请选择', allowClear:true});
}


function bindEvent(){
    $("#add").click(function (){
        initAddUserTypeData();
        initSelectCss();
        $("#all").hide();
        $(".passwordAll").show();
        $("#add-modal").iziModal("open",this);
    });

    $("#saveUser").click(function (){
        saveUser();
    });

    $("#edit").click(function (){
        editUserInit();
    });

    $("#search").click(function (){
        queryUserList(0,10)
    });

    $("#set").click(function (){
        initMenuList();
    })

    if($("#tag").val() == 1007){
        $("#set").show();
    }else{
        $("#set").hide();
    }

    $("#save").click(function (){
        saveSetMenu();
    })


    $("#add-update-from").find("[name='type']").change(function (){
        var value = $(this).val();
        switch (value){
            case "1101":
                $("#add-update-from").find("[name='tag']").html("<option value='1001'>医院管理员</option><option value='1002'>医生</option>");
                break;
            case "1102":
                $("#add-update-from").find("[name='tag']").html("<option value='1003'>厂家管理员</option><option value='1004'>厂家工程师</option>");
                break;
            case "1103":
                $("#add-update-from").find("[name='tag']").html("<option value='1005'>维修商管理员</option><option value='1006'>维修商工程师</option>");
                break;
            case "1105":
                $("#add-update-from").find("[name='tag']").html("<option value='1008'>经销商管理员</option><option value='1009'>经销商</option>");
                break;
            case "1104":
                $("#add-update-from").find("[name='tag']").html("<option value='1007'>平台管理员</option>");
                break;
            case "1106" :
                $("#add-update-from").find("[name='tag']").html("<option value='1010'>卫计委管理员</option><option value='1011'>卫计委</option>");
                break;

        }

        $("#add-update-from").find("[name='tag']").val(null);

        $("#add-update-from").find("[name='tag']").select2({
            language: 'zh-CN',
            placeholder: "请选择",
            allowClear: true
        });

        showType(value,null);
    });
}

function initQueryUserData(){

    var itemHtml = "";
    if(objects.itemList != null && objects.itemList.length>0){
        $.each(objects.itemList,function (index,item) {
            itemHtml+="<option value='"+item.itemId+"'>"+item.item+"</option>"
        });
    }
    $("#queryForm").find("[name='type']").html(itemHtml);
    $("#queryForm").find("[name='type']").val(null);

    $("#queryForm").find("[name='type']").select2({
        language: 'zh-CN',
        placeholder: "请选择类型",
        allowClear: true
    });


    var hospitalHtml = "";
    if(objects.hospitalList != null && objects.hospitalList.length>0){
        $.each(objects.hospitalList,function (index,item) {
            hospitalHtml+="<option value='"+item.hospitalId+"'>"+item.hospitalName+"</option>"
        });
    }

    $("#queryForm").find("[name='hospitalId']").html(hospitalHtml);
    $("#queryForm").find("[name='hospitalId']").val(null);

    $("#queryForm").find("[name='hospitalId']").select2({
        language: 'zh-CN',
        placeholder: "请选择医院",
        allowClear: true
    });

    var manufacturerHtml = "";
    if(objects.manufacturerList != null && objects.manufacturerList.length>0){
        $.each(objects.manufacturerList,function (index,item) {
            manufacturerHtml+="<option value='"+item.manufacturerId+"'>"+item.manufacturerName+"</option>"
        });
    }

    $("#queryForm").find("[name='manufacturerId']").html(manufacturerHtml);
    $("#queryForm").find("[name='manufacturerId']").val(null);

    $("#queryForm").find("[name='manufacturerId']").select2({
        language: 'zh-CN',
        placeholder: "请选择厂商",
        allowClear: true
    });


    var maintainerHtml = "";
    if(objects.maintainerList != null && objects.maintainerList.length>0){
        $.each(objects.maintainerList,function (index,item) {
            maintainerHtml+="<option value='"+item.maintainerId+"'>"+item.maintainerName+"</option>"
        });
    }

    $("#queryForm").find("[name='maintainerId']").html(maintainerHtml);
    $("#queryForm").find("[name='maintainerId']").val(null);

    $("#queryForm").find("[name='maintainerId']").select2({
        language: 'zh-CN',
        placeholder: "请选择维修商",
        allowClear: true
    });

    var supplierHtml = "";
    if(objects.supplierList != null && objects.supplierList.length > 0){
        $.each(objects.supplierList,function (index,item) {
            supplierHtml+="<option value='"+item.supplierId+"'>"+item.supplierName+"</option>"
        });
    }

    $("#queryForm").find("[name='supplierId']").html(supplierHtml);
    $("#queryForm").find("[name='supplierId']").val(null);

    $("#queryForm").find("[name='supplierId']").select2({
        language: 'zh-CN',
        placeholder: "请选择经销商",
        allowClear: true
    });

}



function queryUserList(start,limit){
    var json = {};
    json.start = start;
    json.end = $("#show-count").val();
    var allName = $("#queryForm").find("[name='allName']").val();
    var type = $("#queryForm").find("[name='type']").val();
    var hospitalId = $("#queryForm").find("[name='hospitalId']").val();
    var manufacturerId = $("#queryForm").find("[name='manufacturerId']").val();
    var maintainerId = $("#queryForm").find("[name='maintainerId']").val();
    var supplierId = $("#queryForm").find("[name='supplierId']").val();
    json.allName = allName;
    json.type = type;
    json.hospitalId = hospitalId;
    json.manufacturerId = manufacturerId;
    json.maintainerId = maintainerId;
    json.supplierId = supplierId;
    var url = basePath + "/user/queryUserList";
    publicAjax(url,"POST",json,function (data) {
        if(data.ret == 200){
            bindUserList(data.data.list,0);
            $("#total-count").text(data.data.count);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    })
}


function bindUserList(obj,count) {
    $("#user_table").html("");
    var html = "";
    if(obj == null || obj.length == 0){
        html="<tr><td class='text-center' colspan='12'>暂无数据</td></tr>";
    }

    $.each(obj,function (index,item) {
        html+="<tr><td class='text-center text-muted'>"+(count+index+1)+"</td>" +
            "<td class='text-center text-muted'><input type='checkbox' class='flat-green' name='one' value='"+item.userId+"'></td>" +
            "<td class='text-muted'>"+(item.userName==null?'':item.userName)+"</td>" +
            "<td class='text-muted'>"+(item.mobile==null?'':item.mobile)+"</td>" +
            "<td class='text-muted'>"+(item.realName==null?'':item.realName)+"</td>" +
            "<td class='text-muted'>"+(item.hospitalName==null?'/':item.hospitalName)+"</td>" +
            "<td class='text-muted'>"+(item.manufacturerName==null?'/':item.manufacturerName)+"</td>" +
            "<td class='text-muted'>"+(item.maintainerName==null?'/':item.maintainerName)+"</td>" +
            "<td class='text-muted'>"+(item.delStr==null?'':item.delStr)+"</td>" +
            "<td class='text-muted'>"+(item.typeName==null?'':item.typeName)+"</td>" +
            "<td class='text-muted'>"+(item.tagName==null?'':item.tagName)+"</td>" +
            "</tr>"
    });
    $("#user_table").html(html);
    initDomCss();
}

function initAddUserTypeData(){
    var itemHtml = "";
    if(objects.itemList != null && objects.itemList.length>0){
        $.each(objects.itemList,function (index,item) {
            itemHtml+="<option value='"+item.itemId+"'>"+item.item+"</option>"
        });
    }
    $("#add-update-from").find("[name='type']").html(itemHtml);
    $("#add-update-from").find("[name='type']").val(null);

    $("#add-update-from").find("[name='type']").select2({
        language: 'zh-CN',
        placeholder: "请选择",
        allowClear: true
    });
}

function initDomCss(){
    $('input[type="checkbox"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    $("input[name='one']").on('ifChecked', function(event){
        var current = $(this).parents("tr").index();
        $("[name='one']:checked").each(function(i){
            if($(this).parents("tr").index()!=current){
                $(this).iCheck('uncheck');
            }
        });
    });
}


$("#menu_modal").iziModal({
    title: "菜单列表",
    headerColor: '#00c0ef',
    rtl: false,
    width: 1000,
    zindex: 1042,
    group: '',
    loop: false,
    history: false,
    restoreDefaultContent: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: false,
    fullscreen: true,
    openFullscreen: false,
    closeOnEscape: false,
    onOpening: function () {
    },
    onOpened: function () {
    },
    onClosing: function () {
        $("input[type='checkbox'][name='my1']").iCheck("uncheck");
        $("input[type='checkbox'][name='total1']").iCheck("uncheck");

    },
    onClosed: function () {

    }
});




function myCheckbox1(){

    $('input[type="checkbox"][name="my1"]').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });


    $("input[type='checkbox'][name='total1']").on('ifClicked', function(event){
        $("input[type='checkbox'][name='my1']").iCheck($(this).is(':checked')?'uncheck':'check');
    });
    $("input[type='checkbox'][name='my1']").on('ifChecked', function(event){
        var change = true;
        $("input[type='checkbox'][name='my1']").each(function(){
            if($(this).is(':checked')==false){
                change = false;
            }
        });
        if(change){
            $("input[type='checkbox'][name='total1']").iCheck('check');
        }
    });

    $("input[type='checkbox'][name='my1']").on('ifUnchecked', function(event){
        if($("input[type='checkbox'][name='total1']").is(":checked")){
            $("input[type='checkbox'][name='total1']").iCheck('uncheck');
        }
    });
}



function initModel(){
    $("#add-modal").iziModal({
        title: "编辑用户",
        headerColor: '#00c0ef',
        rtl: false,
        width: 800,
        zindex: 1042,
        iframe: false,
        focusInput: false,
        group: '',
        loop: false,
        history: false,
        restoreDefaultContent: false,
        autoOpen: false, // Boolean, Number
        bodyOverflow: false,
        fullscreen: true,
        openFullscreen: false,
        closeOnEscape: true,
        overlay: true,
        overlayClose: false,
        overlayColor: 'rgba(0, 0, 0, 0.4)',
        onOpening: function () {
            validator();
        },
        onOpened: function () {
        },
        onClosing: function () {
        },
        onClosed: function () {
            $('#add-update-from')[0].reset();
            $("#add-update-from").find("[name='tag']").html("");
            $("#add-update-from").find("[name='userId']").val("");
            $("#add-update-from").data('bootstrapValidator').destroy();

        }
    });
}


function showType(value,id){
    $("#all").show();
    $("#allLable").html("");
    $("#allConent").html("");
    if(value == "1101"){
        $("#allLable").html('医院<span class="text-red">*</span>');
        $("#allConent").html('<select name="hospitalId" style="width: 100%"></select>');
        var html = "";
        $.each(objects.hospitalList,function (index,item) {
            if(item.hospitalId == id){
                html+='<option value="'+item.hospitalId+'" selected>'+item.hospitalName+'</option>';
            }else{
                html+='<option value="'+item.hospitalId+'">'+item.hospitalName+'</option>';
            }

        });
        $("#allConent").find("[name='hospitalId']").html(html);


    }else if(value == "1102"){
        $("#allLable").html('厂商<span class="text-red">*</span>');
        $("#allConent").html('<select name="manufacturerId" style="width: 100%"></select>');
        var html = "";
        $.each(objects.manufacturerList,function (index,item) {
            if(item.manufacturerId == id){
                html+='<option value="'+item.manufacturerId+'" selected>'+item.manufacturerName+'</option>';
            }else{
                html+='<option value="'+item.manufacturerId+'">'+item.manufacturerName+'</option>';
            }

        });
        $("#allConent").find("[name='manufacturerId']").html(html);



    }else if(value == "1103"){
        $("#allLable").html('维修商<span class="text-red">*</span>');
        $("#allConent").html('<select name="maintainerId" style="width: 100%"></select>');
        var html = "";
        $.each(objects.maintainerList,function (index,item) {
            if(item.maintainerId == id){
                html+='<option value="'+item.maintainerId+'" selected>'+item.maintainerName+'</option>';
            }else{
                html+='<option value="'+item.maintainerId+'">'+item.maintainerName+'</option>';
            }

        });
        $("#allConent").find("[name='maintainerId']").html(html);


    }else if(value == "1104"){
        $("#allConent").html("");
        $("#all").hide();
    }else if(value == "1105"){
        $("#allLable").html('经销商<span class="text-red">*</span>');
        $("#allConent").html('<select name="supplierId" style="width: 100%"></select>');
        var html = "";
        $.each(objects.supplierList,function (index,item) {
            if(item.supplierId == id){
                html+='<option value="'+item.supplierId+'" selected>'+item.supplierName+'</option>';
            }else{
                html+='<option value="'+item.supplierId+'">'+item.supplierName+'</option>';
            }

        });
        $("#allConent").find("[name='supplierId']").html(html);
    }

    $("#allConent").find("select").select2({
        language: 'zh-CN',
        placeholder: "请选择",
        allowClear: true
    });
    $("#allConent").find("select").val(null).change();
}


function validator(){
    $('#add-update-from').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            userName: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },
            password: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    stringLength:{
                        max: 16,
                        message: '最多输入16个字符'
                    },
                    identical:{
                        field: 'comfirmPassword',
                        message: '两次密码不相同'
                    }
                }
            }, comfirmPassword: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },stringLength:{
                        max: 16,
                        message: '最多输入16个字符'
                    },
                    identical:{
                        field: 'password',
                        message: '两次密码不相同'
                    }
                }
            },type: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },tag:{
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },mobile: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    },
                    regexp: {
                        regexp: /^1[3|4|5|7|8][0-9]\d{8}$/,
                        message: '请填写正确的手机号码'
                    }
                }
            }
        }
    });
}


var bl = false;
function saveUser(){
    $('#add-update-from').bootstrapValidator('validate');
    if($('#add-update-from').data('bootstrapValidator').isValid()){
        if(!bl){
            bl = true;

            var typeValue = $("#add-update-from").find("[name='type']").val();
            var object = null;
            if(typeValue == "1101"){
                object = $("#add-update-from").find("[name='hospitalId']").val();
                if(object == null || object == ""){
                    flavrShowByTime("请选择医院",null,"danger",false);
                    bl = false;
                    return;
                }
            }else if(typeValue == "1102"){
                object = $("#add-update-from").find("[name='manufacturerId']").val();
                if(object == null || object == ""){
                    flavrShowByTime("请选择厂商",null,"danger",false);
                    bl = false;
                    return;
                }
            }else if(typeValue == "1103"){
                object = $("#add-update-from").find("[name='maintainerId']").val();
                if(object == null || object == ""){
                    flavrShowByTime("请选择维修商",null,"danger",false);
                    bl = false;
                    return;
                }
            }

            var url = basePath+"/user/addOrUpdateUser"
            publicAjax(url,"POST",$("#add-update-from"),function (data) {
                if(data.ret == 200){
                    flavrShowByTime(data.msg,null,"success",false);
                    queryUserList(0,10);
                    $("#add-modal").iziModal("close", this);
                    bl=false;
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                    bl=false;
                }
            })
        }
    }
}


function editUserInit(){
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个用户", null, "danger", false);
        return;
    }
    var json = {"userId":$("input[name='one']:checked").val()};

    var url=basePath+"/user/queryUserInfo";
    publicAjax(url,"POST",json,function (data) {
        bindUserInfo(data.data);
    });
}


function bindUserInfo(obj){
    initAddUserTypeData();
    initSelectCss();
    $("#add-update-from").find("[name='userId']").val(obj.userId);
    $("#add-update-from").find("[name='userName']").val(obj.userName);
    $("#add-update-from").find("[name='realName']").val(obj.realName);
    $(".passwordAll").hide();
    $("#add-update-from").find("[name='mobile']").val(obj.mobile);
    $("#add-update-from").find("[name='type']").val(obj.type);
    var text1 = $("#add-update-from").find("[name='type']").find("option:selected").text();
    $("#add-update-from").find("[name='type']").select2({language:'zh-CN', placeholder:text1, allowClear:true});

    switch (obj.type){
        case 1101:
            $("#add-update-from").find("[name='tag']").html("<option value='1001'>医院管理员</option><option value='1002'>医生</option>");
            break;
        case 1102:
            $("#add-update-from").find("[name='tag']").html("<option value='1003'>厂家管理员</option><option value='1004'>厂家工程师</option>");
            break;
        case 1103:
            $("#add-update-from").find("[name='tag']").html("<option value='1005'>维修商管理员</option><option value='1006'>维修商工程师</option>");
            break;
        case 1105:
            $("#add-update-from").find("[name='tag']").html("<option value='1008'>经销商管理员</option><option value='1009'>经销商</option>");
            break;
        case 1104:
            $("#add-update-from").find("[name='tag']").html("<option value='1007'>平台管理员</option>");
            break;
        case 1106 :
            $("#add-update-from").find("[name='tag']").html("<option value='1010'>卫计委管理员</option><option value='1011'>卫计委</option>");
            break;
    }

    $("#add-update-from").find("[name='tag']").val(obj.tag);
    var text = $("#add-update-from").find("[name='tag']").find("option:selected").text();
    $("#add-update-from").find("[name='tag']").select2({language:'zh-CN', placeholder:text, allowClear:true});

    var all = null;
    if(obj.hospitalId != null){
        all = obj.hospitalId;
    }else if(obj.manufacturerId != null){
        all = obj.manufacturerId;
    }else if(obj.maintainerId){
        all = obj.maintainerId;
    }

    showType(obj.type,obj.all);

    $("#allConent").find("select").val(all);
    var text2 =$("#allConent").find("select").find("option:selected").text();
    $("#allConent").find("select").select2({language:'zh-CN', placeholder:text2, allowClear:true});

    $("input[type='radio'][name='isDel'][value='"+obj.isDel+"']").attr("checked",true);
    $('input[type="radio"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    $("#add-update-from").find("[name='remark']").val(obj.remark);
    $("#add-modal").iziModal("open",this);
}

//分页
function Pagination(total,limit,current){
    $('.M-box3').empty();
    $('.M-box3').pagination({
        totalData:total,
        showData:limit,//数据总数totalData和每页显示的条数showData必须同时配置，否则默认使用总页数pageCount;limit可选值 5 10 20 50
        //pageCount:50,
        current:current,
        jump:true,
        coping:true,
        homePage:'首页',
        endPage:'末页',
        prevContent:'上页',
        nextContent:'下页',
        callback:function(index){
          start = (index.getCurrent()-1)*limit;
          limit = index.getShowData();
          queryUserList(start,limit);
        }
  });
}

function initMenuList(){
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个用户", null, "danger", false);
        return;
    }
    var json = {"userId":$("input[name='one']:checked").val()};
    var url = basePath+"/user/setUserMenu";
    publicAjax(url,"POST",json,function (data){
            if(data.ret == 200){
                bindMenuList(data.data);
            }else{
                flavrShowByTime(data.msg,null,"danger",false);
            }
    });
}

function bindMenuList(obj){
    $("#menu_list").html("");

    var str = "";
    $.each(obj,function (index,item){
        var checked = "";
        if(item.flag == 1){
            checked = "checked";
        }
        str = "<tr>" +
            "<td class='text-muted text-center'><input type='checkbox' class='flat-green' "+checked+" name='my1' value='"+item.id+"'></td>" +
            "<td class='text-muted text-center'>"+(item.level == null ? '' : item.level+1)+"</td>" +
            "<td class='text-muted text-center'>"+(item.path == null ? '' : item.path)+"</td>" +
            "<td class='text-muted text-center'>"+(item.name == null ? '' : item.name)+"</td>" +
            "</tr>"
        $("#menu_list").append(str);
    });
    myCheckbox1();
    $("#menu_modal").iziModal("open",this);
}


function saveSetMenu(){
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个用户", null, "danger", false);
        return;
    }
    var json = {"userId":$("input[name='one']:checked").val()};

    var value= "";
    $.each($("input[name='my1']:checked"),function (index,item){
        value+=$(item).val()+",";
    });

    json.urlId = value;
    var url = basePath+"/user/saveSetMenu";
    publicAjax(url,"POST",json,function (data){
        if(data.ret == 200){
            flavrShowByTime(data.msg, null, "success", false);
        }else{
            flavrShowByTime(data.msg, null, "danger", false);
        }
    })


}